<?php

$this->AddHook('get_inbox_requests', 'GetInboxRequests');
function GetInboxRequests($bot)
{
   $bot->SendMsg('# Getting Inbox Requests');
   RefreshInboxRequests($bot);
}
function CURLGetFile($url, $XMLconfig)
{
   $ch = curl_init($url);
   curl_setopt($ch, CURLOPT_HEADER, true);
   curl_setopt($ch, CURLOPT_HEADER, "Transfer-Encoding: chunked"); //necessary in case of big JSON files
   curl_setopt($ch, CURLOPT_TIMEOUT, 10);
   curl_setopt($ch, CURLOPT_USERAGENT, $XMLconfig->UserAgent);
   curl_setopt($ch, CURLOPT_COOKIE, $XMLconfig->Cookie);
   curl_setopt($ch, CURLOPT_POST, false);
   curl_setopt($ch, CURLOPT_HTTPGET, true);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   $output = curl_exec($ch);
   curl_close($ch);

   return $output;
}
function CURLGetFile2($url, $XMLconfig, $hash, $eventid)
{

   //$refer = 'http://fb-0.cityville.zynga.com/flash.php?';
   $refer = 'http://web-zc1.cityville.zynga.com/flash.php?';

   $refer .= 'isOuterIframe=1';
   $refer .= '&zySnid=1';
   $refer .= '&zyAuthHash=' . $XMLconfig->zyAuthHash;
   $refer .= '&zySig=' . $XMLconfig->zySig;

   $url .= '&zySnid=1';
   $url .= '&zyAuthHash=' . $XMLconfig->zyAuthHash;
   $url .= '&zySig=' . $XMLconfig->zySig;
   $url .= '&all=all';
   $url .= '&action=accept';
   $url .= '&eventTypeId=' . $eventid;
   $url .= '&eventIds%5B%5D=' . $hash;
   $url .= '&zy_ctoken=null';

   $ch = curl_init($url);
   curl_setopt($ch, CURLOPT_HEADER, true);
   curl_setopt($ch, CURLOPT_HEADER, "Transfer-Encoding: chunked"); //necessary in case of big JSON files
   curl_setopt($ch, CURLOPT_TIMEOUT, 10);
   curl_setopt($ch, CURLOPT_REFERER, $refer);
   curl_setopt($ch, CURLOPT_USERAGENT, $XMLconfig->UserAgent);
   curl_setopt($ch, CURLOPT_COOKIE, $XMLconfig->Cookie);
   curl_setopt($ch, CURLOPT_POST, false);
   curl_setopt($ch, CURLOPT_HTTPGET, true);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   $output = curl_exec($ch);
   curl_close($ch);

   return $output;
}
function CURLGetFile3($url, $XMLconfig, $hash, $eventid)
{

   //$refer = 'http://fb-0.cityville.zynga.com/flash.php?';
   $refer = 'http://web-zc1.cityville.zynga.com/flash.php?';

   $refer .= 'isOuterIframe=1';
   $refer .= '&zySnid=1';
   $refer .= '&zyAuthHash=' . $XMLconfig->zyAuthHash;
   $refer .= '&zySig=' . $XMLconfig->zySig;

   $url .= '&zySnid=1';
   $url .= '&zyAuthHash=' . $XMLconfig->zyAuthHash;
   $url .= '&zySig=' . $XMLconfig->zySig;
   $url .= '&all=all';
   $url .= '&action=ignore';
   $url .= '&eventTypeId=' . $eventid;
   $url .= '&eventIds%5B%5D=' . $hash;
   $url .= '&zy_ctoken=null';

   $ch = curl_init($url);
   curl_setopt($ch, CURLOPT_HEADER, true);
   curl_setopt($ch, CURLOPT_HEADER, "Transfer-Encoding: chunked"); //necessary in case of big JSON files
   curl_setopt($ch, CURLOPT_TIMEOUT, 10);
   curl_setopt($ch, CURLOPT_REFERER, $refer);
   curl_setopt($ch, CURLOPT_USERAGENT, $XMLconfig->UserAgent);
   curl_setopt($ch, CURLOPT_COOKIE, $XMLconfig->Cookie);
   curl_setopt($ch, CURLOPT_POST, false);
   curl_setopt($ch, CURLOPT_HTTPGET, true);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   $output = curl_exec($ch);
   curl_close($ch);

   return $output;
}
function RefreshInboxRequests($bot)
{
   $imagePath = substr($_SERVER["PHP_SELF"], 0, strpos($_SERVER["PHP_SELF"], "/"));
   $XMLconfigFile = $imagePath . "Profiles\\" . $bot->zySnuid . '__Zy.xml';
   $XMLconfig = new Zend_Config_Xml($XMLconfigFile);

   //creating db - poested here to prevent the sql error
   $bot->ld->ExecQuery("drop table if exists 'Inbox'");
   $bot->ld->ExecQuery("CREATE TABLE if not exists [Inbox] ([hash] NVARCHAR(60) NULL, [type_id] INTERGER, [type_text] NVARCHAR(50) NULL, [sender] NUMBER, [accept] NVARCHAR(250), [ignore] NVARCHAR(250), [picture] NVARCHAR(250), [material] VARCHAR(80) NULL)");

   //****************************************************************
   //http://fb-0.cityville.zynga.com/zsc/evt_data.php?
   //&zySnid=1
   //&zyAuthHash=ed1d2dbacb8233ec3e4765c88436c9f1
   //&zySig=361001f8d3026d287dc7fe259cfe72d0

   //$url = 'http://fb-0.cityville.zynga.com/zsc/evt_data.php?';
   $url = 'http://fb-zc1.cityville.zynga.com/zsc/evt_data.php?';
   $url .= '&zySnid=1';
   $url .= '&zyAuthHash=' . $XMLconfig->zyAuthHash;
   $url .= '&zySig=' . $XMLconfig->zySig;

   $request = CURLGetFile($url, $XMLconfig);
   $request = json_decode($request, true);
   if ($request == null)
   {
     $bot->SendMsg('# no pending requests found in your Inbox.');
     return;
   }
   foreach($request as $hash=>$item)
   {
     $data=$item['data']['0'];
     $metadata=$item['metadata'];

     //[hash] NVARCHAR(60) NULL
     //[type_id] INTERGER,
     //[type_text] NVARCHAR(50) NULL,
     //[sender] INTERGER,
     //[accept] NVARCHAR(250),
     //[ignore] NVARCHAR(250),
     //[picture] NVARCHAR(250),
     //[material] VARCHAR(80) NULL)

     if ($metadata['sender']=="1:") $metadata['sender'] = "1";

     $EQ = 'INSERT INTO Inbox VALUES (';
     $EQ .= '"' . $hash . '",';
     $EQ .= $metadata['type_id'] . ',';
     $EQ .= '"' . $metadata['type_text'] . '",';
     $EQ .= $metadata['sender'] . ',';
     $EQ .= '"' . $data['button_post'] . '",';
     $EQ .= '"' . $data['ignore_post'] . '",';
     $EQ .= '"' . $data['image'] . '",';
     $EQ .= '"' . $metadata['contentID'] . '")';
     //$bot->SendMsg($EQ);
     $bot->ld->ExecQuery($EQ);
   }
}

$this->AddHook('start_inbox', 'ProcessInboxRequests');
function ProcessInboxRequests($bot)
{
   if($bot->firstrun)
   {
      return;
   }
   $imagePath = substr($_SERVER["PHP_SELF"], 0, strpos($_SERVER["PHP_SELF"], "/"));
   $XMLconfigFile = $imagePath . "Profiles\\" . $bot->zySnuid . '__Zy.xml';
   $XMLconfig = new Zend_Config_Xml($XMLconfigFile);

   $data = $bot->ld->GetPlSettings("inbox");
   if($data == null) return;

   if ((!isset($data->gifts) || !$data->gifts) &&
       (!isset($data->help) || !$data->help) &&
       (!isset($data->crew) || !$data->crew) &&
       (!isset($data->factory) || !$data->factory) &&
       (!isset($data->vip) || !$data->vip))
   {
     return;
   }

   $rlist = array();
   $sel = $bot->ld->GetSelect('SELECT * FROM Inbox order by type_id, type_text');
   foreach ($sel as $selitem)
   { $rlist[] = $selitem; }
       //[hash]
       //[type_id] INTERGER,
       //[type_text] NVARCHAR(50) NULL,
       //[sender] INTERGER,
       //[accept] NVARCHAR(250),
       //[ignore] NVARCHAR(250),
       //[picture] NVARCHAR(250),
       //[material] VARCHAR(80) NULL)

   //processing gifts
   $msg  = $bot->irc('u').$bot->irc('b');
   $msg .= $bot->irc('cc').'2';
   $msg .= $bot->irc('ff').'13,5'.chr(232).$bot->irc('ff').'14,5';
   $msg .= 'Starting Plugin: INBOX';
   $bot->SendMsg($msg);


   //processing Gifts ==========================================================
   if (isset($data->gifts) && $data->gifts)
   {
     $again=true;
     while ($again)
     {
       $again=false;
       $lastgift = "";
       foreach ($rlist as $key=>$item)
       {
         if (($item['type_id'] != 13002) || ($item['type_text'] != "Gifts" && $item['type_text'] != "Geschenke")) continue;
         if (isset($data->gifts) && $data->gifts)
         {
           if (($lastgift != "") &&
               ($item['material']==$lastgift) &&
               (isset($data->giftsNot) && $data->giftsNot) &&
               (substr($item['material'],0,12) != "mysterygift_"))
           { $again=true; continue;}
         }

         $lastgift=$item['material'];
         $url = $item['accept'];

         unset($rlist[$key]); //remove the request from the processing list

         //send the request and get the response
         $bot->SendMsg('[INBOX] '.$bot->irc('b').'Procesing: '.$item['type_text'].' from '.(string)$item['sender']);
         $response = CURLGetFile2($url, $XMLconfig, $item['hash'], (string)$item['type_id'] );
         //echo $response;
         $response = json_decode($response, true);
         //print_r($response);
         if ($response == null)
         {
           $bot->SendMsg('[INBOX] Response ERROR');
           //continue;
         }
         foreach($response as $index=>$ritem)
         {
           $lines = explode("\n", $ritem['message']);
           $msg = trim(strip_tags($lines[0]));
           $bot->SendMsg('[INBOX] #Message: '.$msg);
           if (isset($ritem['success']) && ($ritem['success']==true))
           {
             if (isset($ritem['itemName'])) $bot->SendMsg('[INBOX] #Reward: '.$ritem['itemName']. ' ['.$ritem['loot'].' x'.$ritem['lootAmount'].']');
           }
         }
       }//end each
     }//end while
   }
   //ignore Gifts ==========================================================
   if (isset($data->ignoregifts) && $data->ignoregifts)
   {
     $again=true;
     while ($again)
     {
       $again=false;
       $lastgift = "";
       foreach ($rlist as $key=>$item)
       {
         if (($item['type_id'] != 13002) || ($item['type_text'] != "Gifts" && $item['type_text'] != "Geschenke")) continue;
         if (isset($data->ignoregifts) && $data->ignoregifts)
		 {
           if (($lastgift != "") &&
               ($item['material']==$lastgift) &&
               (substr($item['material'],0,12) != "mysterygift_"))
           { $again=true; continue;}
         }
		 $lastgift=$item['material'];
         $url = $item['ignore'];

         unset($rlist[$key]); //remove the request from the processing list

         //send the request and get the response
         $bot->SendMsg('[INBOX] '.$bot->irc('b').'Procesing: Ignore '.$item['type_text'].' from '.(string)$item['sender']);
         $response = CURLGetFile3($url, $XMLconfig, $item['hash'], (string)$item['type_id'] );
         //echo $response;
         $response = json_decode($response, true);
         //print_r($response);
         if ($response == null)
         {
           $bot->SendMsg('[INBOX] Response ERROR');
           //continue;
         }
         foreach($response as $index=>$ritem)
         {
           $lines = explode("\n", $ritem['message']);
           $msg = trim(strip_tags($lines[0]));
           $bot->SendMsg('[INBOX] #Message: '.$msg);
           if (isset($ritem['success']) && ($ritem['success']==true))
           {
             if (isset($ritem['itemName'])) $bot->SendMsg('[INBOX] #Reward: '.$ritem['itemName']. ' ['.$ritem['loot'].' x'.$ritem['lootAmount'].']');
           }
         }
       }//end each
     }//end while
   }

   //processing Help Requests===================================================
   if (isset($data->help) && $data->help)
   {
     $i=0;
     $again=true;
     while ($again)
     {
       $again=false;
       $lastgift = "";
       foreach ($rlist as $key=>$item)
       {
         if (!in_array($item['type_id'], array(13002,13043)) || ($item['type_text'] != "Help Requests" && $item['type_text'] != "Hilfeanfragen")) continue;
         if (isset($data->help) && $data->help)
         {
           if (($lastgift != "") &&
               ($item['material']==$lastgift) &&
               (isset($data->helpNot) && $data->helpNot))
           { $again=true; continue;}
         }

         $i++; //number of actions so far
         $lastgift=$item['material'];
         $url = $item['accept'];

         unset($rlist[$key]); //remove the request from the processing list

         //send the request and get the response
         $bot->SendMsg('[INBOX] '.$bot->irc('b').'Procesing: '.$item['type_text'].' from '.(string)$item['sender']);
         $response = CURLGetFile2($url, $XMLconfig, $item['hash'], (string)$item['type_id'] );
         //echo $response;
         $response = json_decode($response, true);
         //print_r($response);
         if ($response == null)
         {
           $bot->SendMsg('[INBOX] Response ERROR=null');
           //continue;
         }
         foreach($response as $index=>$ritem)
         {
           $lines = explode("\n", $ritem['message']);
           $msg = trim(strip_tags($lines[0]));
           $bot->SendMsg('[INBOX] #Message: '.$msg);
           if (isset($ritem['success']) && ($ritem['success']==true))
           {
             if (isset($ritem['itemName'])) $bot->SendMsg('[INBOX] #Reward: '.$ritem['itemName']. ' ['.$ritem['loot'].' x'.$ritem['lootAmount'].']');
           }
         }
         if (isset($data->helpN) && ($data->helpN > 0) && ($i > $data->helpN))
         {
           $bot->SendMsg('[INBOX] Max Help actions number ('.$data->helpN.') reached');
           break 2;
         }
       }//end each
     }//end while
   }
   //ignore Help Requests===================================================
   if (isset($data->ignorehelp) && $data->ignorehelp)
   {
     $again=true;
     while ($again)
     {
       $again=false;
       $lastgift = "";
       foreach ($rlist as $key=>$item)
       {
         if (!in_array($item['type_id'], array(13002,13043)) || ($item['type_text'] != "Help Requests" && $item['type_text'] != "Hilfeanfragen")) continue;
         if (isset($data->ignorehelp) && $data->ignorehelp)
         {
           if (($lastgift != "") &&
               ($item['material']==$lastgift))
           { $again=true; continue;}
         }

         $lastgift=$item['material'];
         $url = $item['ignore'];

         unset($rlist[$key]); //remove the request from the processing list

         //send the request and get the response
         $bot->SendMsg('[INBOX] '.$bot->irc('b').'Procesing: Ignore '.$item['type_text'].' from '.(string)$item['sender']);
         $response = CURLGetFile3($url, $XMLconfig, $item['hash'], (string)$item['type_id'] );
         //echo $response;
         $response = json_decode($response, true);
         //print_r($response);
         if ($response == null)
         {
           $bot->SendMsg('[INBOX] Response ERROR=null');
           //continue;
         }
         foreach($response as $index=>$ritem)
         {
           $lines = explode("\n", $ritem['message']);
           $msg = trim(strip_tags($lines[0]));
           $bot->SendMsg('[INBOX] #Message: '.$msg);
           if (isset($ritem['success']) && ($ritem['success']==true))
           {
             if (isset($ritem['itemName'])) $bot->SendMsg('[INBOX] #Reward: '.$ritem['itemName']. ' ['.$ritem['loot'].' x'.$ritem['lootAmount'].']');
           }
         }
       }//end each
     }//end while
   }

   //processing Neighbor Invitation ============================================
   if (isset($data->neighbor) && $data->neighbor)
   {
     foreach ($rlist as $key=>$item)
     {
       if ($item['type_id'] != 13011) continue;

       $url = $item['accept'];

       unset($rlist[$key]); //remove the request from the processing list

       //send the request and get the response
       $bot->SendMsg('[INBOX] '.$bot->irc('b').'Procesing: '.$item['type_text'].' from '.(string)$item['sender']);
       $response = CURLGetFile2($url, $XMLconfig, $item['hash'], (string)$item['type_id'] );
       //echo $response;
       $response = json_decode($response, true);
       //print_r($response);
       if ($response == null)
       {
         $bot->SendMsg('[INBOX] Response ERROR=null');
         continue;
       }
       foreach($response as $index=>$ritem)
       {
           $lines = explode("\n", $ritem['message']);
           $msg = trim(strip_tags($lines[0]));
           $bot->SendMsg('[INBOX] #Message: '.$msg);
           if (isset($ritem['success']) && ($ritem['success']==true))
           {
             if (isset($ritem['itemName'])) $bot->SendMsg('[INBOX] #Reward: '.$ritem['itemName']. ' ['.$ritem['loot'].' x'.$ritem['lootAmount'].']');
           }
       }
     }//end each
   }

   //processing Crew Invites ===================================================
   if (isset($data->crew) && $data->crew)
   {
     foreach ($rlist as $key=>$item)
     {
       if ($item['type_id'] != 13022) continue;

       $url = $item['accept'];

       unset($rlist[$key]); //remove the request from the processing list

       //send the request and get the response
       $bot->SendMsg('[INBOX] '.$bot->irc('b').'Procesing: '.$item['type_text'].' from '.(string)$item['sender']);
       $response = CURLGetFile2($url, $XMLconfig, $item['hash'], (string)$item['type_id'] );
       //echo $response;
       $response = json_decode($response, true);
       //print_r($response);
       if ($response == null)
       {
         $bot->SendMsg('[INBOX] Response ERROR=null');
         continue;
       }
       foreach($response as $index=>$ritem)
       {
           $lines = explode("\n", $ritem['message']);
           $msg = trim(strip_tags($lines[0]));
           $bot->SendMsg('[INBOX] #Message: '.$msg);
           if (isset($ritem['success']) && ($ritem['success']==true))
           {
             if (isset($ritem['itemName'])) $bot->SendMsg('[INBOX] #Reward: '.$ritem['itemName']. ' ['.$ritem['loot'].' x'.$ritem['lootAmount'].']');
           }
       }
     }//end each
   }

   //processing Factory invites ================================================
   if (isset($data->factory) && $data->factory)
   {
     foreach ($rlist as $key=>$item)
     {
       if ($item['type_id'] != 13028) continue;

       $url = $item['accept'];

       unset($rlist[$key]); //remove the request from the processing list

       //send the request and get the response
       $bot->SendMsg('[INBOX] '.$bot->irc('b').'Procesing: '.$item['type_text'].' from '.(string)$item['sender']);
       $response = CURLGetFile2($url, $XMLconfig, $item['hash'], (string)$item['type_id'] );
       //echo $response;
       $response = json_decode($response, true);
       //print_r($response);
       if ($response == null)
       {
         $bot->SendMsg('[INBOX] Response ERROR=null');
         continue;
       }
       foreach($response as $index=>$ritem)
       {
           $lines = explode("\n", $ritem['message']);
           $msg = trim(strip_tags($lines[0]));
           $bot->SendMsg('[INBOX] #Message: '.$msg);
           if (isset($ritem['success']) && ($ritem['success']==true))
           {
             if (isset($ritem['itemName'])) $bot->SendMsg('[INBOX] #Reward: '.$ritem['itemName']. ' ['.$ritem['loot'].' x'.$ritem['lootAmount'].']');
           }
       }
     }//end each
   }

   //processing VIP requests ===================================================
   if (isset($data->vip) && $data->vip)
   {
     foreach ($rlist as $key=>$item)
     {
       if ($item['type_id'] != 13050) continue;

       $url = $item['accept'];

       unset($rlist[$key]); //remove the request from the processing list

       //send the request and get the response
       $bot->SendMsg('[INBOX] '.$bot->irc('b').'Procesing: '.$item['type_text'].' from '.(string)$item['sender']);
       $response = CURLGetFile2($url, $XMLconfig, $item['hash'], (string)$item['type_id'] );
       //echo $response;
       $response = json_decode($response, true);
       //print_r($response);
       if ($response == null)
       {
         $bot->SendMsg('[INBOX] Response ERROR=null');
         continue;
       }
       foreach($response as $index=>$ritem)
       {
         //$msg = $ritem['message'];
         //if (stripos($msg, 'type="text/javascript"')>0)
         //{
         //  $msg = substr($msg,0,strpos($msg, '<script')-1);
         //}
           $lines = explode("\n", $ritem['message']);
           $msg = trim(strip_tags($lines[0]));
           $bot->SendMsg('[INBOX] #Message: '.$msg);
           if (isset($ritem['success']) && ($ritem['success']==true))
           {
             if (isset($ritem['itemName'])) $bot->SendMsg('[INBOX] #Reward: '.$ritem['itemName']. ' ['.$ritem['loot'].' x'.$ritem['lootAmount'].']');
           }
       }
     }//end each
   }

   // all done, refresh the plugin
   RefreshInboxRequests($bot); //refreshing the list to save on db
   $bot->pm->RefreshMePlugin("Inbox"); //refreshing the plugin page

}

	//==========================================================================


?>